package vineet.java.code.linklist;

public class MyLinkList<T>
{
	private Node<T> start ;
	
	public MyLinkList()
	{
		
	}
	public MyLinkList(Node<T> start)
	{
		this.start = start ;
	}
	public void add(Node<T> node)
	{
		if(this.start == null)
		{
			this.start = node;
			this.start.setNext(null);
		}
		else
		{
			Node<T> tmp = this.start ;
			while(tmp.getNext() != null)
			{
				tmp = tmp.getNext();
			}
			node.setNext(null);
			tmp.setNext(node) ;
		}
	}
	public void add(T value)
	{
		if(this.start == null)
		{
			this.start = new Node<T>(value);
			this.start.setNext(null);
		}
		else
		{
			Node<T> tmp = this.start ;
			while(tmp.getNext() != null)
			{
				tmp = tmp.getNext();
			}
			Node<T> nextNode = new Node<T>(value);
			nextNode.setNext(null);
			tmp.setNext(nextNode) ;
		}
	}
	public void delete(T value)
	{
		Node<T> tmp = this.start ;
		Node<T> previous = this.start ;
		if(tmp == null)
		{
			System.out.println("You can't delete, List is empty");
		}
		else
		{
			while(tmp != null)
			{
				if(tmp.getData() == value)
				{
					if(tmp == previous)
					{
						this.start = tmp.getNext();
						tmp = null ;
					}
					else
					{
						previous.setNext(tmp.getNext());
						tmp = null ;
						break ;
					}
				}
				previous = tmp;
				tmp = tmp.getNext();
			}
		}
	}
	public void print()
	{
		Node<T> tmp = this.start ;
		if(this.start == null)
		{
			System.out.println("Link List is empty");
		}
		while(tmp != null)
		{
			System.out.print(tmp.getData()+" =>");
			tmp = tmp.getNext();
		}
	}
	public int getLength()
	{
		int length = 0 ;
		Node<T> tmp = this.start ;
		while(tmp != null)
		{
			tmp = tmp.getNext();
			length += 1 ;
		}
		return length ;
	}
	public Node<T> delete(int place)
	{
		Node<T> tmp = this.start ;
		Node<T> previous = this.start ;
		if(tmp == null)
		{
			System.out.println("You can't delete, List is empty");
			return null ;
		}
		else if(place  == 1)
		{
			this.start = tmp.getNext();
		}
		else if(this.getLength() < place)
		{
			System.out.println("Not mutch node left");
		}
		else
		{
			for(int i=1; i < place; i ++)
			{
				previous = tmp ;
				tmp = tmp.getNext();
			}
			previous.setNext(tmp.getNext());
		}
		return tmp ;
	}
	public Node<T> getStart() {
		return start;
	}
	public void setStart(Node<T> start) {
		this.start = start;
	}
}
